﻿#region License
/*
Copyright (c) <2012> <Nercoding>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Original Code by Gastric of Dawnsong
 */
#endregion
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using AC2_MultiClient.Managers;
using System.IO;
using AC2_MultiClient.Forms;
using AC2_MultiClient.Mouse;
using System.Diagnostics;
using System.Net.Sockets;
using AC2_MultiClient.Events;

namespace AC2_MultiClient
{
    public partial class AC2MultiClient : Form
    {
        #region Properties
        private static AC2MultiClient This { get; set; }
        private Dictionary<string, string> UserList = new Dictionary<string, string>();
        private ProcessMonitor Monitor { get; set; }
        public static List<Client> Clients = new List<Client>();
        private int ClientProcess = 0;
        private MemoryManager MemMgr { get; set; }
        private Timer MaintenanceTimer { get; set; }
        /// <summary>
        /// Our main form
        /// </summary>
        public AC2MultiClient()
        {
            This = this;
            InitializeComponent();
            this.FormClosing += new FormClosingEventHandler(AC2MultiClient_FormClosing);
            MaintenanceTimer = new Timer();
            MaintenanceTimer.Interval = 30000;
            MaintenanceTimer.Tick += new EventHandler(MaintenanceTimer_Tick);
            MaintenanceTimer.Start();
        }
        #endregion
        #region Form Load
        private void AC2MultiClient_Load(object sender, EventArgs e)
        {
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

            try
            {
                //Debug = new DebugMenu();
                //Debug.Show();
                // Begin our process monitor
                Monitor = new ProcessMonitor();
                Monitor.Start();
                // Create our custom event
                Monitor.IncommingProcess += new ProcessMonitor.ChangingHandler(Monitor_IncommingProcess);
                // make sure our config directory exists

                if (!Globals.CreateSaveDir())
                {
                    DialogResult result = MessageBox.Show("Unable to create config directory, maybe run this as an administrator ?", "Configuration Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    if (result == System.Windows.Forms.DialogResult.OK) { this.Close(); }
                }
                // Now check our xml config
                XmlManager.Load();

                // Load our servers
                foreach (string s in XmlManager.ServerList)
                {
                    ServerList.Items.Add(s);
                }
                // Now select the first item as default
                this.ServerList.Items[0].Selected = true;

                // Add user names
                foreach (string u in XmlManager.UserList)
                {
                    if (!userBox.Items.Contains(u))
                    {
                        // Add the names to our userlist
                        UserList.Add(u, ""); // no Password saved
                        userBox.Items.Add(u);
                    }
                }
                // Select the first user 
                userBox.Text = userBox.Items[0].ToString();

                // Subcribe a a drop down list change
                userBox.SelectedIndexChanged += new EventHandler(userBox_SelectedIndexChanged);
            }                // On first run if user just tries to login he gets this because no Directories
            // Need to open the dir box first
            catch
            {
                MessageBox.Show("Error Loading Config Options, you need to add a valid Asheron's Call 2 Directory", "Error in AC2MultiClient_Load", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                DirectoryForm f = new DirectoryForm();
                f.Show();
            }
        }
        #endregion
        #region Login
        private void btn_Login_Click(object sender, EventArgs e)
        {
            if (userBox.Text == string.Empty) { return; }
            if (passBox.Text == string.Empty) { return; }
            if (ServerList.SelectedItems[0].Text == string.Empty) { return; }

            if (IsUserLoggedIn(userBox.Text))
            {
                MessageBox.Show("User already logged in.","Username is logged in.", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }
            // Is the user selected in our users list, if not add him.
            if (!XmlManager.IsUserInConfig(userBox.Text)) { XmlManager.AddUser(userBox.Text); }
            // If the username is not in our drop down list, add it
            if (!UserList.ContainsKey(userBox.Text)) 
            {
                UserList.Add(userBox.Text, passBox.Text);
                userBox.Items.Add(userBox.Text);
            }
            else
            {
                // We do contain this username, is the password the same ?, if not update it
                if (UserList[userBox.Text] != passBox.Text) { UserList[userBox.Text] = passBox.Text; }
            }
            // Do we have an available client loc ?
            string Next = GetNextClientLoc();
            if (Next != string.Empty)
            {
                try
                {
                    // Ok then we need to start this launcher and then wait
                    // Turn off login button
                    this.btn_Login.Enabled = false;
                    string user = userBox.Text;
                    // Start our launcher
                    Launcher l = new Launcher(Next, userBox.Text, passBox.Text, ServerList.Items[0].Text);
                    // Wait for our client to begin
                    System.Threading.Thread thread = new System.Threading.Thread(delegate()
                    {
                        PerformLogin(user, Next);
                    });
                    thread.IsBackground = true;
                    thread.Start();
                   
                }
                catch { MessageBox.Show("Unable to Create Client.", "Error in Login Creation", MessageBoxButtons.OK, MessageBoxIcon.Stop); return; }
                
            }
            else 
            {
                MessageBox.Show("No Available directory.");
                return; 
            }
        }
        #endregion
        #region Toolbar
        /// <summary>
        /// Exit's this application
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void quitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        /// <summary>
        /// Opens our directory copy form
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void directoriesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DirectoryForm f = new DirectoryForm();
            f.Show();
        }
        #endregion
        #region Misc
        private void userBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            // When we choose another selection in our user drop down list, change to
            // the temp password we have for it
            try
            {
                passBox.Text = UserList[userBox.Text];
            }
            catch { }
        }

        private void deleteUser_Click(object sender, EventArgs e)
        {
            try
            {
                // This will delete the currently selected username
                // First remove it from our xml
                if (XmlManager.IsUserInConfig(userBox.Text)) { XmlManager.RemoveUser(userBox.Text); }
                // Now remove it from our username list
                if (UserList.ContainsKey(userBox.Text)) { UserList.Remove(userBox.Text); }
                // Now remove it from our drop down list
                if (userBox.Items.Contains(userBox.Text)) { userBox.Items.Remove(userBox.Text); }

                // Now select the first name we have as default
                userBox.SelectedIndex = 0;
            }
            catch { }
        }
        /// <summary>
        ///  Checks to see if we have a client logged in with the currently selected user name
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public bool IsUserLoggedIn(string user)
        {
            foreach (Client c in Clients)
            {
                if (c.ClientName == user)
                {
                    return true;
                }
            }
            return false;
        }
        /// <summary>
        /// We need the next client location not in use.
        /// </summary>
        private string GetNextClientLoc()
        {
            string next = string.Empty;
            List<string> UsedPaths = new List<string>();
            foreach (Client c in Clients)
            {
                UsedPaths.Add(c.UsedDir);
            }
            try
            {
                List<string> result = XmlManager.Directories.Except(UsedPaths).ToList();
                next = result[0];
            }
            catch { }
            return next;
        }


        private void btn_Client_Click(object sender, EventArgs e)
        {
            StringBuilder info = new StringBuilder();
            foreach (Client c in Clients)
            {
                try
                {
                    info.AppendLine("Username: " + c.ClientName);
                    info.AppendLine("Using Client Location: " + c.UsedDir);
                    info.AppendLine("Process: " + c.ClientProcess.Id);
                    info.AppendLine("Logged in: " + c.GetLoggedInTime());
                }
                catch { MessageBox.Show("Unable to generate Client information.", "Error in Gathering Client info.", MessageBoxButtons.OK, MessageBoxIcon.Stop); return; }
            }
            MessageBox.Show(info.ToString());
        }
        #endregion
        #region Form Closing
        /// <summary>
        /// Actions to perform when the form is closing
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AC2MultiClient_FormClosing(object sender, FormClosingEventArgs e)
        {
            // Have to stop our watcher
            Monitor.Dispose();
        }
        #endregion
        private void PerformLogin(string user, string path)
        {
            
            Stopwatch wait = new Stopwatch();
            Process p = null;
            wait.Start();
            while (wait.Elapsed.Seconds != 15)
            {
                if (ClientProcess != 0)
                {
                    // Add to our list
                    p = Process.GetProcessById(ClientProcess);
                    Client c = new Client(user, path, p);
                    // We need to slow this down here
                    WaitForXSeconds(3);
                    //WriteToDebug("(" + user + ") Client Created", Color.Black);
                    IntPtr point = PerformMouseFunction.FindWindow("Asheron's Call 2", "Asheron's Call 2");
                    // In case 
                    c.WindowHandle = point;
                    Clients.Add(c);
                    WindowManager.SetForegroundWindow(point);
                    //WriteToDebug("(" + user + ") Setting Foreground Window", Color.Black);
                    WindowManager.ForceTitleChange(point, WindowManager.NewWindowName());
                    //WriteToDebug("(" + user + ") Changed Window Title", Color.Black);
                    WindowManager.ByPassScreen(point);
                    //WriteToDebug("(" + user + ") ByPassed Screen", Color.Black);
                    // Turn back on login button
                    ToggleLogonButton(true);
                    ClientProcess = 0;
                    break;
                }
            }
            ToggleLogonButton(true);
            wait.Stop();
            wait.Reset();
            if (p != null)
            {
                StartMemoryManager(p);
            }
        }
        private void ToggleLogonButton(bool toggle)
        {
            if (this.btn_Login.InvokeRequired)
            {
                this.btn_Login.Invoke((MethodInvoker)
                    delegate
                    {
                        this.btn_Login.Enabled = toggle;
                    });
            }
            else
            {
                this.btn_Login.Enabled = toggle;
            }
        }

        private bool WaitForXSeconds(int x)
        {
            Stopwatch watch = new Stopwatch();
            watch.Start();
            while (watch.Elapsed.Seconds != x)
            {
            }
            watch.Stop();
            return true;
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            About a = new About();
            a.textBoxDescription.Text = "AC2 Multi Client Application \n"+
                     "Makes logging into the server alot easier \n"+
                     "as well as managing multiple game locations.";
            a.labelCopyright.Text = "Copyright 2012 - 2013 Nerdcoding";
            a.labelCompanyName.Text = "Written by Gastric of Dawnsong";
            a.Show();
        }
        private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
        }
        private static void CreateMiniDump()
        {
            using (FileStream fs = new FileStream(Globals.CrashDump, FileMode.Create))
            {
                using (System.Diagnostics.Process process = System.Diagnostics.Process.GetCurrentProcess())
                {
                    MINIDUMP_TYPE.MiniDumpWriteDump(process.Handle,
                                                     process.Id,
                                                     fs.SafeFileHandle.DangerousGetHandle(),
                                                     MINIDUMP_TYPE.MiniDumpNormal,
                                                     IntPtr.Zero,
                                                     IntPtr.Zero,
                                                     IntPtr.Zero);
                }
            }
        }
        
        private void Monitor_IncommingProcess(object sender, ProcessEventArgs e)
        {
            ClientProcess = e.Client.Id;
        }
       
        private void StartMemoryManager(Process p)
        {
            MemMgr = new MemoryManager(p);
            MemMgr.Start();
        }
        private void MaintenanceTimer_Tick(object sender, EventArgs e)
        {
            // Clean up our Clients if needed
            List<int> ProcessesInUse = new List<int>();
            foreach (Client c in Clients) { ProcessesInUse.Add(c.ClientProcess.Id); }
            List<int> CurrentProcessesRunning = new List<int>();
            Process[] pro = Process.GetProcessesByName("ac2client");
            foreach (Process p in pro) { CurrentProcessesRunning.Add(p.Id); }
            // We have 2 lists now they should match if not we have a client that stuck around.
            List<int> result = ProcessesInUse.Except(CurrentProcessesRunning).ToList();
            if (result.Count != 0)
            {
                // We have clients in our list that dont have an active ac2client assigned to them, so lets remove those who dont.
                for (int i = 0; i < result.Count; i++) { Clients.RemoveAll(x => x.ClientProcess.Id == result[i]); }
            }
        }
    }
}
